<?php

namespace app\api\controller;


use app\common\model\AdModel;
use app\common\model\CarLabelModel;
use app\common\model\CarLicenseModel;
use app\common\model\CarLicenseMoreModel;
use app\common\model\CarSeriesModel;
use app\common\model\InviteModel;
use app\common\model\MemberModel;
use app\common\model\UserCarModel;
use app\sms\controller\SendSms;
use think\Request;

class SellController extends BaseController
{


    /**
     * @param Request $request
     * @return \think\response\Json
     */
    public function index(Request $request)
    {
        //失败返回数据
        return backError("用户名错误！");
    }


    /**
     * 发布二手车
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function publish(Request $request)
    {
        set_time_limit(0);
        //必填
        $id = $request->id; //id
        $user_id = $request->user["uid"]; //用户ID
        $imgList = $request->img_file; //用户自传图片
        $brand_id = $request->brand_id; //车辆品牌
        $series_id = $request->car_type_id; //车辆款型
        $car_id = $request->car_id; //款型ID
        //$car_id = 0; //款型ID
        $car_color = $request->car_color;
        $car_level = $request->car_level; //车辆类型（没用）
        $card_time = $request->cardTime; //上牌时间
        $mileage = $request->lc; //行驶里程
        $price = $request->price; //售价
        $carCase = $request->carCase; //变速箱 （没用）
        $strongTime = $request->carQXTime; //交强险到期时间
        $yearlyTime = $request->carNJTime; //年检到期时间
        $head_img = $request->headImg; //首图
        $vin = $request->vin; //行驶证vin
        //可选
        $card_come = $request->pz ?: ""; //拍照归属地
        $transfer_times = $request->gh ?: 0; //过户次数
        $pledge = $request->dy ?: "无"; //过户次数
        $nature = $request->xz ?: "非运营"; //过户次数
        $standard = $request->pf; //排放标准
        $address = $request->address; //看车地点
        $lat = $request->lat; //纬度
        $lng = $request->lng; //经度
        $add_conf = $request->lab; //加装配置
        //必填
        $content = $request->content; //车况描述
        $real_name = $request->real_name;  //联系人姓名
        $mobile = $request->mobile;  //联系方式
        $inviteCode = $request->code; //推荐码

        $is_buy = $request->is_buy ? 1 : 0; //是否愿意卖给车商
        //判断
        if (empty($imgList) && $id == 0) return backError("参数错误！");
        if (count($imgList) == 0 && $id == 0) return backError("参数错误！");
        if (empty($head_img)) return backError("参数错误！");
        if (empty($brand_id) && $id == 0) return backError("参数错误！");
        if (empty($series_id) && $id == 0) return backError("参数错误！");
        if (empty($car_id) && $id == 0) return backError("参数错误，请选择车辆款型！");
        if (empty($car_color)) return backError("参数错误！");
        //if (empty($car_level)) return backError("参数错误！");
        //if (empty($card_time)) return backError("参数错误！");
//        if (empty($strongTime)) return backError("参数错误！");
//        if (empty($yearlyTime)) return backError("参数错误！");
        //if (empty($vin)) return backError("参数错误！");
        if (empty($mileage)) return backError("参数错误！");
        if (empty($price)) return backError("参数错误！");
        if (empty($content)) return backError("参数错误！");
        if (empty($real_name)) return backError("参数错误！");
        if (empty($mobile)) return backError("参数错误！");

        if ($id > 0) {
            $info = UserCarModel::where("user_id", $user_id)
                ->where('status', 'in', '0,1')
                ->where('sell_status', 0)
                ->get($id);

            if (empty($info)) {
                return backError("参数错误！");
            }

            $status = $this->editCar($request, $info);

            if ($status) {
                return backSuccess([], "编辑成功！");
            } else {
                return backError("编辑失败，请稍后再试！");
            }
        }


        $img = [];
        foreach ($imgList as $vo) {
            $s = $this->userUpload($vo["content"]);
            if ($s["code"]) {
                $imgUrl["thumb"] = $s["url"];
                $img[] = $imgUrl;
            }

        }

        if (count($img) == 0) return backError("参数错误！");

        $autoTime = getSystem("auto_push_time");
        $publish_time = time() + (60 * $autoTime);

        /*$cl = CarLicenseModel::where('vin', '=', $vin)->find();

        $card_come = mb_substr($cl["car_number"], 0, 1);
        $nature = $cl["using_nature"];
        $card_time = mb_substr($cl["reg_time"], 0, 4) . "-" . mb_substr($cl["reg_time"], 4, 2) . "-" . mb_substr($cl["reg_time"], 6, 2);*/


        $data = [
            'user_id' => $user_id,
            'brand_id' => $brand_id,
            'series_id' => $series_id,
            'car_id' => $car_id,
            'car_level' => $car_level,
            'car_color' => $car_color,
            'card_time' => strtotime($card_time),
            'strong_time' => strtotime($strongTime),
            'yearly_time' => strtotime($yearlyTime),
            'mileage' => $mileage,
            'price' => $price,
            'card_come' => $card_come,
            'transfer_times' => $transfer_times,
            'address' => $address,
            'add_conf' => json_encode($add_conf),
            'content' => $content,
            'real_name' => $real_name,
            'mobile' => $mobile,
            'img_list' => json_encode($img),
            'pledge' => $pledge,
            'nature' => $nature,
            'invite_code' => $inviteCode,
            'car_case' => $carCase,
            'standard' => $standard,
            'is_buy' => $is_buy,
            'lat' => $lat,
            'lng' => $lng,
            'create_time' => time(),
            'refresh_time' => time(),
            'publish_time' => $publish_time,
            'head_img' => $head_img,
            'vin' => $vin,
            'status' => 1,
        ];

        $res = new UserCarModel();
        $status = $res->adds($data);

        if ($status['status']) {
            $status = SendSms::send(getSystem("server_phone"), $request->user["mobile"], 3);

            //发布奖励将在48小时内审核通过后发放
            $carMoney = getSystem("get_money") ? getSystem("get_money") : 0;
            $msg="发布成功，等待审核！";
            if($carMoney>0){
                $msg="发布奖励将在48小时内审核通过后发放!";
            }

            return backSuccess([], $msg);
        }
        return backError("发布失败，请稍后再试！");
    }

    /**
     * 编辑发布车车辆
     * @param $request
     * @param $info
     * @return bool
     * @throws \think\exception\DbException
     */
    private function editCar($request, $info)
    {
        $id = $request->id; //id
        $car_color = $request->car_color;
        $card_time = $request->cardTime; //上牌时间
        $mileage = $request->lc; //行驶里程
        $price = $request->price; //售价
        $strongTime = $request->carQXTime; //交强险到期时间
        $yearlyTime = $request->carNJTime; //年检到期时间
        $head_img = $request->headImg; //首图
        //可选
        $card_come = $request->pz ?: ""; //拍照归属地
        $transfer_times = $request->gh ?: 0; //过户次数
        $pledge = $request->dy ?: "无"; //过户次数
        $nature = $request->xz ?: "非运营"; //过户次数
        $standard = $request->pf; //排放标准
        $address = $request->address; //看车地点
        $add_conf = $request->lab; //加装配置
        $lat = $request->lat; //纬度
        $lng = $request->lng; //经度
        //必填
        $content = $request->content; //车况描述
        $real_name = $request->real_name;  //联系人姓名
        $mobile = $request->mobile;  //联系方式
        $is_buy = $request->is_buy ? 1 : 0; //是否愿意卖给车商

        $autoTime = getSystem("auto_push_time");
        $publish_time = time() + (60 * $autoTime);

        $data = [
            'id' => $id,
            'car_color' => $car_color,
            'strong_time' => strtotime($strongTime),
            'yearly_time' => strtotime($yearlyTime),
            'mileage' => $mileage,
            'old_price' => $info->price,
            'price' => $price,
            'transfer_times' => $transfer_times,
            'address' => $address,
            'add_conf' => json_encode($add_conf),
            'real_name' => $real_name,
            'mobile' => $mobile,
            'pledge' => $pledge,
            'standard' => $standard,
            'is_buy' => $is_buy,
            'lat' => $lat,
            'lng' => $lng,
            'head_img' => $head_img,
            'status' => 1,
            'publish_time' => $publish_time,
        ];

        if (!empty($content)) {
            $data["content"] = $content;
        }

        $res = new UserCarModel();
        $status = $res->adds($data);


        if ($status['status']) {
            return true;
        }
        return false;
    }

    /**
     * 用户上传
     * @param $file
     * @return array
     */
    private function userUpload($file, $dir_path = '/uploads/users/')
    {
        set_time_limit(0);

        $up_dir_url = '.' . $dir_path;

        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url, 0777, true);
        }

        $dir_path = $dir_path . date('Ymd') . '/';
        $up_dir_url = '.' . $dir_path;
        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url, 0777, true);
        }

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)) {
            $type = $result[2];

            if (in_array($type, config("img_ext_arr"))) {
                $new_file = $up_dir_url . md5($file) . '.' . $type;
                $fileUrl = $dir_path . md5($file) . '.' . $type;

                $info = file_put_contents($new_file, base64_decode(str_replace($result[1], '', $file)));
                if ($info) {
                    return ["code" => 1, "msg" => "上传成功", 'url' => $fileUrl];
                } else {
                    return ["code" => 0, "msg" => "上传失败"];
                }
            } else {
                //文件类型错误
                return ["code" => 0, "msg" => "格式错误！"];
            }
        }
    }

    /**
     * 获取发布车源信息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception\DbException
     */
    public function getPublishInfo(Request $request)
    {
        if (empty($request->id)) {
            return backError("参数错误！");
        }

        $id = $request->id;
        $uid = $request->user["uid"];


        $info = UserCarModel::where("user_id", $uid)
            ->where('status', 'in', '0,1')
            ->where('sell_status', 0)
            ->get($id);

        if (empty($info)) {
            return backError("参数错误！");
        }

        if (!empty($info->img_list)) {
            $info->img_list = json_decode($info->img_list, true);
        }
        if (!empty($info->add_conf)) {
            $info->add_conf = json_decode($info->add_conf, true);
        }

        return backSuccess($info);
    }

    /**
     * 获取汽车加装配置
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCarLabel()
    {
        $list = CarLabelModel::where('status', CarLabelModel::SHOW_STATUS)
            ->select();

        return backSuccess($list);
    }

    /**
     * 百度图片识别接口
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function carCard(Request $request)
    {
        set_time_limit(0);
        $img = $request->cardImg;
        $uid = $request->user["uid"];

        if (empty($img)) return backError("参数错误！");

        $imgCode = $this->imgToBase64('.' . $img);

        if (empty($imgCode)) return backError("参数错误！");

        //使用$token变量存储百度云的授权码
        $token = '24.54a08d308e52d66058a969945a0f20b5.2592000.1600964940.282335-21607740';
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=' . $token;
        $params = array(
            'image' => $imgCode
        );
        //调用百度云获取行驶证各字段内容
        $res = http_curl($url, $params, 1);

        if (isset($res['error_code']) && $res['error_code'] > 0) {
            return backError("行驶证识别失败，请按确保拍摄清晰！");
        }

        if (isset($res['words_result']) && $res['words_result_num'] > 0) {
            $wordsData = $res["words_result"];
            $vin = isset($wordsData["车辆识别代号"]) ? $wordsData["车辆识别代号"]["words"] : '';

            if (empty($vin)) return backError("行驶证识别失败，请按确保拍摄清晰！");

            //$vin = "LDCT81X4XE1016241";

            //查询vin码是否已存在
            $carData = CarLicenseModel::where('vin', '=', $vin)->find();

            if (empty($carData)) {
                //保存行驶证信息
                $carData = [
                    'user_id' => $uid,
                    'vin' => $vin,
                    'address' => isset($wordsData["住址"]) ? $wordsData["住址"]["words"] : '',
                    'release_time' => isset($wordsData["发证日期"]) ? $wordsData["发证日期"]["words"] : '',
                    'brand_models' => isset($wordsData["品牌型号"]) ? $wordsData["品牌型号"]["words"] : '',
                    'car_type' => isset($wordsData["车辆类型"]) ? $wordsData["车辆类型"]["words"] : '',
                    'real_name' => isset($wordsData["所有人"]) ? $wordsData["所有人"]["words"] : '',
                    'using_nature' => isset($wordsData["使用性质"]) ? $wordsData["使用性质"]["words"] : '',
                    'engine_number' => isset($wordsData["发动机号码"]) ? $wordsData["发动机号码"]["words"] : '',
                    'car_number' => isset($wordsData["号牌号码"]) ? $wordsData["号牌号码"]["words"] : '',
                    'reg_time' => isset($wordsData["注册日期"]) ? $wordsData["注册日期"]["words"] : '',
                    'vin_url' => $img,
                ];

                CarLicenseModel::adds($carData);
            }

            //行驶证识别详细信息数组
            $carMore = $this->getCardMore($vin, $uid);

            if (!$carMore) {
                return backError("行驶证识别失败，请按确保拍摄清晰！");
            }
        } else {
            return backError("行驶证识别失败，请按确保拍摄清晰！");
        }

        $cs = CarSeriesModel::field('brand_id,series_id,series_name')->where('series_name', 'like', "%{$carMore['car_line']}")->find();

        $car = [
            "series_name" => "",
            "brand_id" => 0,
            "series_id" => 0,
        ];

        if (!empty($cs)) {
            $car = [
                "series_name" => $cs->series_name,
                "brand_id" => $cs->brand_id,
                "series_id" => $cs->series_id,
            ];
        }


        $data = [
            'vinCar' => $carData,
            'carMore' => $carMore,
            'car' => $car,
        ];

        return backSuccess($data);
    }

    /**
     * 获取图片的Base64编码
     * @param $img_file 传入本地图片地址
     * @return string
     */
    private function imgToBase64($img_file)
    {
        $img_base64 = '';
        if (file_exists($img_file)) {
            $img_string = file_get_contents($img_file);
            $img_base64 = base64_encode($img_string);
        }

        return $img_base64; //返回图片的base64
    }

    /**
     * 调用阿里云获取VIN码查询信息
     * @param $vin
     * @param int $user_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getCardMore($vin, $user_id = 0)
    {

//        $info=CarLicenseMoreModel::where('vin','=',$vin)->find();
//        return $info;

        $host = "https://ali-vin.showapi.com/vin";
        $appcode = "6c11d13edcea40eb9a4f62870e345533";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "vin=" . $vin;

        $res = http_curl($host . '?' . $querys, false, 0, $headers);

        if (!isset($res["showapi_res_body"])) return false;

        $data = $res["showapi_res_body"];
        if (isset($data['ret_code']) && $data['ret_code'] == 0) {
            $vin = strtoupper($data['vin']);

            $inData = [
                "user_id" => $user_id,
                "vin" => $vin,
                "brand_name" => $data["brand_name"],
                "model_name" => $data["model_name"],
                "sale_name" => $data["sale_name"],
                "car_type" => $data["car_type"],
                "engine_type" => $data["engine_type"],
                "car_line" => $data["car_line"],
                "power" => $data["power"],
                "jet_type" => $data["jet_type"],
                "fuel_Type" => $data["fuel_Type"],
                "transmission_type" => $data["transmission_type"],
                "cylinder_number" => $data["cylinder_number"],
                "cylinder_form" => $data["cylinder_form"],
                "output_volume" => $data["output_volume"],
                "made_year" => $data["made_year"],
                "made_month" => $data["made_month"],
                "stop_year" => $data["stop_year"],
                "effluent_standard" => $data["effluent_standard"],
                "fuel_num" => $data["fuel_num"],
                "guiding_price" => $data["guiding_price"],
                "year" => $data["year"],
                "air_bag" => $data["air_bag"],
                "seat_num" => $data["seat_num"],
                "vehicle_level" => $data["vehicle_level"],
                "door_num" => $data["door_num"],
                "car_body" => $data["car_body"],
                "manufacturer" => $data["manufacturer"],
                "gears_num" => $data["gears_num"],
                "car_weight" => $data["car_weight"],
                "assembly_factory" => $data["assembly_factory"],
                "remark" => $data["remark"],
                "drive_style" => $data["drive_style"],
            ];
            $info = CarLicenseMoreModel::where('vin', '=', $vin)->find();
            if (empty($info)) {
                CarLicenseMoreModel::adds($inData);
            }

            return $info;
        } else {
            return false;
        }
    }

}
